// pages/blog/blog.js
let userInfo = {};
const MAX_LIMIT = 20;
let total = 0;
let keyWord = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    modalShow: false,
    blogList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this._getBlog(keyWord);
  },

  // 获取搜索关键字
  onSearchKeyWord(e) {
    keyWord = e.detail.keyWord.trim();
  },
  // 搜索
  onSearch(e) {
    this.setData({
      blogList: []
    });
    this._getBlog(keyWord);
  },

  // 加载博客数据
  _getBlog(keyWord) {
    wx.showLoading({
      title: '加载中...',
    });

    wx.cloud.callFunction({
      name: "blog2",
      data: {
        $url: "getBlogList",
        start: this.data.blogList.length,
        count: MAX_LIMIT,
        keyWord
      }
    }).then((res) => {
      // console.log(res);
      wx.hideLoading();
      let result = res.result;
      this.setData({
        blogList: this.data.blogList.concat(result.data)
      });
      total = result.total;
      wx.stopPullDownRefresh();
    });
  },

  // 发布信息
  onPublisth() {
    wx.getSetting({
      success: (res) => {
        // console.log(res);
        if (res.authSetting["scope.userInfo"]) {
          wx.getUserInfo({
            success: (res) => {
              // console.log(res);
              this.onLoginSuccess({
                userInfo: res.userInfo
              });
            }
          });
        } else {
          this.setData({
            modalShow: true
          })
        }
      }
    });
  },

  // 登陆成功
  onLoginSuccess(e) {
    // console.log(e);
    let detail = {};
    if (e.userInfo) {
      detail = e.userInfo;
    } else {
      detail = e.detail;
    }

    wx.navigateTo({
      url: `../blog-edit/blog-edit?nickName=${detail.nickName}&avatarUrl=${detail.avatarUrl}`,
    });
  },

  // 登陆失败
  onLoginFail(e) {
    wx.showModal({
      title: '授权用户才能发布博客',
      content: '',
    });
  },
  // 页面跳转
  onComment(e) {
    // console.log(e);
    const blogId = e.currentTarget.dataset.blogid
    wx.navigateTo({
      url: `../blog-comment/blog-comment?blogId=${blogId}`,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      blogList: []
    });
    total = 0;
    this._getBlog(keyWord);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.blogList < total) {
      this._getBlog(keyWord);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    // console.log(e);
    const blog = e.target.dataset.blog;
    const blogId = e.target.dataset.blogid;
    return {
      title: blog.content,
      path: `/pages/blog-comment/blog-comment?blogId=${blogId}`
    }
  }
})